<template>
	<view>
		<!-- logo -->
		<view class="imgBox">
			<image src="../../static/images/logo1.png" mode=""></image>
		</view>
		<!-- 手机号 -->
		<view class="phoneBox">
			<u--input placeholder="请输入手机号" shape="circle" v-model="phone"></u--input>
		</view>
		<!-- 验证码 -->
		<view class="phoneBox">
			<u-input placeholder="请输入验证码" v-model="code" shape="circle">
				<template slot="suffix">
					<u-button :text="msg" type="success" size="mini" @click="sendCode" :disabled="isShow"></u-button>
				</template>
			</u-input>
		</view>
		<!-- 登录 -->
		<view class="phoneBox">
			<u-button type="primary" text="登录" @click="login"></u-button>
		</view>
	</view>
</template>

<script>
	//引入接口地址
	import {
		getSms,
		smsLogin
	} from "../../request/app.js"
	export default {
		data() {
			return {
				phone: "",
				code: "",
				reCode: "",
				isShow: false,
				msg: "获取验证码",
				num: 30
			}
		},
		methods: {
			//点击发送验证码
			sendCode() {
				let reg = /^1[3|4|5|7|8|9][0-9]\d{4,11}$/
				// 正则验证手机号
				if (!reg.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机格式',
						icon: "error"
					})
					return;
				}
				//判断本地是否有code
				if (uni.getStorageSync("code")) {
					this.reCode = uni.getStorageSync("code")
					//验证码提示
					uni.showToast({
						title: "验证码：" + this.reCode
					})
				} else {
					//调用验证码接口
					getSms(this.phone).then(res => {
						console.log(res);
						if (res.data.code == 200) {
							this.reCode = res.data.list.code
							//验证码提示
							uni.showToast({
								title: "验证码：" + this.reCode
							})
							//将验证码存入本地
							uni.setStorageSync("code", res.data.list.code)
						}
					})
				}
				//开启定时器，更改按钮样式
				let timer = setInterval(() => {
					this.num--
					this.msg = `${this.num}秒后，重新获取`
					this.isShow = true
					if (this.num < 1) {
						//清除定时器
						clearInterval(timer)
						this.msg = "获取验证码"
						this.isShow = false
						this.num = 30
					}
				}, 1000)
			},
			//点击登录
			login() {
				//判断本地是否有code
				if (uni.getStorageSync("code")) {
					this.reCode = uni.getStorageSync("code")
				} else {
					uni.showToast({
						title: "请先获取验证码",
						icon: "error"
					})
					return
				}
				if (!this.phone || this.code != this.reCode) {
					uni.showToast({
						title: "请输入正确的手机号或验证码",
						icon: "none"
					})
				} else {
					//调用登录接口
					smsLogin({
						phone: this.phone
					}).then(res => {
						console.log(res);
						if (res.data.code == 200) {
							//将响应信息存入本地
							uni.setStorageSync("userInfo", res.data.list)
							//跳转到首页
							uni.reLaunch({
								url: "/pages/home/home"
							})
						}
					})
				}
			}
		}
	}
</script>

<style>
	.imgBox {
		margin-top: 300rpx;
		margin-bottom: 100rpx;
		width: 100%;
		text-align: center;
	}

	.imgBox>image {
		width: 350rpx;
		height: 120rpx;
	}

	.phoneBox {
		padding-left: 40rpx;
		padding-right: 40rpx;
		margin-bottom: 50rpx;
	}
</style>
